/*
 *		Listener.java
 *
 *		Created on 08 JAN 2005 by Duane Bolick
 *		ver 1.0
 *
 *		This class listens on the socket and parses the incoming messages,
 *		updating the CurrentRobotState object appropriately.
 *	
 */

package edu.wsu.KheperaSimulator;

import java.io.*;
import java.util.*;

public class Listener implements Runnable
{
    private BufferedReader reader;
    private CurrentRobotState state;
	private long timeout;
    
    int pCount = 0;
    private MessageProcessor[] processorThreads = new MessageProcessor[20];

    String inc;


    public Listener( long _timeout, BufferedReader _reader, CurrentRobotState _state )
    {
    	timeout = _timeout;
        state = _state;
        reader = _reader;
     	inc = "";
    }

	public void run()
	{
		while( state.sessionStatus != ClientConfiguration.TIMEOUT && state.sessionStatus != ClientConfiguration.BROKEN)
		{
			read();
		
			try
			{
				Thread.sleep(timeout);
			}
			
			catch(Exception e)
			{
			}
		}
	}
   
   	public void read()
   	{
   		try
   		{
   			inc = reader.readLine();
   		}
   		
   		catch(Exception e)
   		{
   			state.sessionStatus = ClientConfiguration.BROKEN;
   			System.out.println("\nConnection Lost");
   			System.exit(0);
		}

		if( inc == null )
   		{
   			state.sessionStatus = ClientConfiguration.BROKEN;
   			return;
   		}

		if ( ClientConfiguration.DEBUG ) System.out.println("listener hears:" + inc);

   		if( inc.length() < 2 )
   			return;

		

   		if( pCount >= 10 )
   			pCount = 0;

   		processorThreads[pCount] = new MessageProcessor( state, inc );
		processorThreads[pCount].start();
		pCount++;
    }
     
   
}
